<?php

namespace App\Http\Middleware;

use App\Models\User;
use Closure;
use Config , Cookie;

class ApiAuth
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @param  string|null  $guard
     * @return mixed
     */
    public function handle($request , Closure $next)
    {
        $token = Cookie::get(Config::get('session.taoke_user_cookie'));
        if(!$token){
            $token = $request->get('token');
        }

        if($token == 'test123'){
            $userInfo = User::where('id', 1)->first();
        }else {
            $userInfo = \Cache::get($token);
        }

        if(!isset($userInfo->id)){
            $loginUrl = Config::get('app.url').'/api/wechat/login?appid='.$request->get('appid');
            return response()->json(['error' => '没有登录' , 'redirect' => [$loginUrl] ]);
        }

        global $g_uid;

        $g_uid = $userInfo->id;

        $response = $next($request);

        return $response;
    }
}
